//Global var to avoid any conflicts
var CRUMINA = {};
$(document).ready(function () {

    (function ($) {
        // USE STRICT
        "use strict";

        //----------------------------------------------------/
        // Predefined Variables
        //----------------------------------------------------/
        var $window = $(window),
            $document = $(document),
            $body = $('body'),
            $sidebar = $('.fixed-sidebar'),
            $preloader = $('#hellopreloader');

        /* -----------------------
         * Preloader
         * --------------------- */

        CRUMINA.preloader = function () {
            $window.scrollTop(0);
            console.info("加载中。。。。。。。。。。");
            setTimeout(function () {
                $preloader.fadeOut(800);
            }, 500);
            return false;
        };

        //Scroll to top.
        jQuery('.back-to-top').on('click', function () {
            $('html,body').animate({
                scrollTop: 0
            }, 1200);
            return false;
        });


        /* -----------------------
        * Input Number Quantity
           * --------------------- */

        $(document).on("click", ".quantity-plus", function () {
            var val = parseInt($(this).prev('input').val());
            $(this).prev('input').val(val + 1).change();
            return false;
        });

        $(document).on("click", ".quantity-minus", function () {
            var val = parseInt($(this).next('input').val());
            if (val !== 1) {
                $(this).next('input').val(val - 1).change();
            }
            return false;
        });


        /* -----------------------------
         Custom input type="number"
         https://bootsnipp.com/snippets/featured/bootstrap-number-spinner-on-click-hold
         * ---------------------------*/

        $(function () {
            var action;
            $(document).on("touchstart mousedown", ".number-spinner button", function () {
                var btn = $(this);
                var input = btn.closest('.number-spinner').find('input');
                btn.closest('.number-spinner').find('button').prop("disabled", false);

                if (btn.attr('data-dir') == 'up') {
                    action = setInterval(function () {
                        if (input.attr('max') == undefined || parseInt(input.val()) < parseInt(input.attr('max'))) {
                            input.val(parseInt(input.val()) + 1);
                        } else {
                            btn.prop("disabled", true);
                            clearInterval(action);
                        }
                    }, 50);
                } else {
                    action = setInterval(function () {
                        if (input.attr('min') == undefined || parseInt(input.val()) > parseInt(input.attr('min'))) {
                            input.val(parseInt(input.val()) - 1);
                        } else {
                            btn.prop("disabled", true);
                            clearInterval(action);
                        }
                    }, 50);
                }
            });
            $(document).on("touchend mouseup", ".number-spinner button", function () {
                clearInterval(action);
            });
        });

        /* -----------------------------
         * Toggle functions
         * ---------------------------*/

        $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
            var target = $(e.target).attr("href"); // activated tab
            if ('#events' === target) {
                $('.fc-state-active').click();
            }
        });

        // Toggle aside panels
        $(document).on('click', ".js-sidebar-open", function () {
            var mobileWidthApp = $('body').outerWidth();
            if (mobileWidthApp <= 560) {
                $(this).closest('body').find('.popup-chat-responsive').removeClass('open-chat');
            }

            $(this).toggleClass('active');
            $(this).closest($sidebar).toggleClass('open');
            return false;
        });

        // Close on "Esc" click
        $window.keydown(function (eventObject) {
            if (eventObject.which == 27 && $sidebar.is(':visible')) {
                $sidebar.removeClass('open');
            }
        });

        // Close on click outside elements.
        $document.on('click', function (event) {
            if (!$(event.target).closest($sidebar).length && $sidebar.is(':visible')) {
                $sidebar.removeClass('open');
            }
        });

        // Toggle inline popups

        var $popup = $('.window-popup');


        $(document).on('click', ".js-open-popup", function (event) {
            var target_popup = $(this).data('popup-target');
            var current_popup = $popup.filter(target_popup);
            var offset = $(this).offset();
            current_popup.addClass('open');
            current_popup.css('top', (offset.top - (current_popup.innerHeight() / 2)));
            $body.addClass('overlay-enable');
            return false;
        });


        // Close on "Esc" click
        $window.keydown(function (eventObject) {
            if (eventObject.which == 27) {
                $popup.removeClass('open');
                $body.removeClass('overlay-enable');
                $('.profile-menu').removeClass('expanded-menu');
                $('.popup-chat-responsive').removeClass('open-chat');
                $('.profile-settings-responsive').removeClass('open');
                $('.header-menu').removeClass('open');
                $('.js-sidebar-open').removeClass('active');
            }
        });

        // Close on click outside elements.
        $document.on('click', function (event) {
            if (!$(event.target).closest($popup).length) {
                $popup.removeClass('open');
                $body.removeClass('overlay-enable');
                $('.profile-menu').removeClass('expanded-menu');
                $('.header-menu').removeClass('open');
                $('.profile-settings-responsive').removeClass('open');
            }
        });

        // Close active tab on second click.
        $('[data-toggle=tab]').on('click', function () {
            /*$body.toggleClass('body--fixed');*/
            if ($(this).hasClass('active') && $(this).closest('ul').hasClass('mobile-app-tabs')) {
                $($(this).attr("href")).toggleClass('active');
                $(this).removeClass('active');
                return false;
            }
        });


        // Close on "X" click
        $(document).on('click', ".js-close-popup", function () {
            $(this).closest($popup).removeClass('open');
            $body.removeClass('overlay-enable');
            return false
        });

        $(document).on('click', ".profile-settings-open", function () {
            $('.profile-settings-responsive').toggleClass('open');
            return false
        });

        $(document).on('click', ".js-expanded-menu", function () {
            $('.header-menu').toggleClass('expanded-menu');
            return false
        });

        // 点击好友进行聊天
        $(document).on("click", ".js-chat-open", function () {
            if($(this).hasClass("olymp-little-delete")){
                $('.popup-chat-responsive').toggleClass('open-chat');
                return false;
            }
            console.log("点击聊天。。。。。。。。。。" + $(this));
            // 先清除<ul>标签中的内容，再获取用户与该好友的聊天记录
            $("#chat-message-field").empty();
            $("#message-content").html("");
            let friendName = $(this).children().find("p").text();
            if(friendName === "" || friendName == null){
                friendName = $(this).prev().children("a").text();
            }

            let myName = $("#loginedUserName").text();
            var $now = $(this);
            $.ajax({
                type: "POST",
                url: "chat/get/" + myName + "/" + friendName,
                async: false,
                success: function (result) {
                    let jsonResult = jQuery.parseJSON(result);
                    console.log(jsonResult);
                    for (let i = 0; i < jsonResult.length; i++) {
                        let json = jQuery.parseJSON(jsonResult[i].messageContent);
                        if (json.A === myName) {
                            let imgPath = $("#user-img").attr("src");
                            // 如果发送方是我
                            createChatEle(json, 1, imgPath)
                        } else {
                            let imgPath = $now.children(".author-thumb").find("img").attr("src");
                            if(imgPath === undefined){
                                // 证明不是点击好友列表聊天
                                imgPath = $now.prev().prev().children("img").attr("src");
                            }
                            console.log("好友图片地址：" + imgPath);
                            // 如果发送方不是我
                            createChatEle(json, 0, imgPath);
                        }
                    }
                },
                error: function (e) {
                }
            });
            // 设置聊天的标题，显示与谁在聊天
            $("#chat-title").text(friendName);

            // 获得好友状态
            let status = $(this).children().find("span").attr("class");
            if(status === undefined){
                $("#chat-users-large").children("li").each(function () {
                    if($(this).children(".author-thumb").children("p").text() === friendName){
                        // 找到了对应的用户，获取状态
                        status = $(this).children(".author-thumb").children("div").children("span").attr("class");
                        return true;
                    }
                });
                readChatMessage($now);
            }
            console.log("好友状态为：" + status);
            // 设置聊天好友的状态
            $("#chat-status").removeClass();
            $("#chat-status").addClass(status);
            console.log(friendName);
            $('.popup-chat-responsive').toggleClass('open-chat');

            return false;
        });


        $(document).on('click', ".js-chat-close", function () {
            $('.popup-chat-responsive').removeClass('open-chat');
            return false
        });

        $(document).on('click', ".js-open-responsive-menu", function () {
            $('.header-menu').toggleClass('open');
            return false
        });
        $(document).on('click', ".js-close-responsive-menu", function () {
            $('.header-menu').removeClass('open');
            return false
        });


        /* -----------------------------
             * Scrollmagic scenes animation
        * ---------------------------*/

        CRUMINA.CallToActionAnimation = function () {
            var controller = new ScrollMagic.Controller();

            new ScrollMagic.Scene({triggerElement: ".call-to-action-animation"})
                .setVelocity(".first-img", {opacity: 1, bottom: "0", scale: "1"}, 1200)
                .triggerHook(1)
                .addTo(controller);

            new ScrollMagic.Scene({triggerElement: ".call-to-action-animation"})
                .setVelocity(".second-img", {opacity: 1, bottom: "50%", right: "40%"}, 1500)
                .triggerHook(1)
                .addTo(controller);
        };

        CRUMINA.ImgScaleAnimation = function () {
            var controller = new ScrollMagic.Controller();

            new ScrollMagic.Scene({triggerElement: ".img-scale-animation"})
                .setVelocity(".main-img", {opacity: 1, scale: "1"}, 200)
                .triggerHook(0.3)
                .addTo(controller);

            new ScrollMagic.Scene({triggerElement: ".img-scale-animation"})
                .setVelocity(".first-img1", {opacity: 1, scale: "1"}, 1200)
                .triggerHook(0.8)
                .addTo(controller);

            new ScrollMagic.Scene({triggerElement: ".img-scale-animation"})
                .setVelocity(".second-img1", {opacity: 1, scale: "1"}, 1200)
                .triggerHook(1.1)
                .addTo(controller);

            new ScrollMagic.Scene({triggerElement: ".img-scale-animation"})
                .setVelocity(".third-img1", {opacity: 1, scale: "1"}, 1200)
                .triggerHook(1.4)
                .addTo(controller);
        };

        CRUMINA.SubscribeAnimation = function () {
            var controller = new ScrollMagic.Controller();

            new ScrollMagic.Scene({triggerElement: ".subscribe-animation"})
                .setVelocity(".plane", {opacity: 1, bottom: "auto", top: "-20", left: "50%", scale: "1"}, 1200)
                .triggerHook(1)
                .addTo(controller);

        };

        CRUMINA.PlanerAnimation = function () {
            var controller = new ScrollMagic.Controller();

            new ScrollMagic.Scene({triggerElement: ".planer-animation"})
                .setVelocity(".planer", {opacity: 1, left: "80%", scale: "1"}, 2000)
                .triggerHook(0.1)
                .addTo(controller);

        };

        CRUMINA.ContactAnimationAnimation = function () {
            var controller = new ScrollMagic.Controller();

            new ScrollMagic.Scene({triggerElement: ".contact-form-animation"})
                .setVelocity(".crew", {opacity: 1, left: "77%", scale: "1"}, 1000)
                .triggerHook(0.1)
                .addTo(controller);
        };

        CRUMINA.perfectScrollbarInit = function () {
            var $chatContainer = $('.popup-chat-responsive .mCustomScrollbar');
            var $containers = $('.mCustomScrollbar');

            $containers.perfectScrollbar({wheelPropagation: false});

            if (!$chatContainer.length) {
                return;
            }

            $chatContainer.scrollTop($chatContainer.prop("scrollHeight"));
            $chatContainer.perfectScrollbar('update');
        };


        /* -----------------------------
     * Responsive
     * ---------------------------*/
        CRUMINA.responsive = {
            $profilePanel: null,
            $desktopContainerPanel: null,
            $responsiveContainerPanel: null,
            init: function () {
                this.$profilePanel = jQuery('#profile-panel');
                this.$desktopContainerPanel = jQuery('#desktop-container-panel > .ui-block');
                this.$responsiveContainerPanel = jQuery('#responsive-container-panel .ui-block');
                this.update();
            },
            mixPanel: function () {
                if (window.matchMedia("(max-width: 1024px)").matches) {
                    this.$responsiveContainerPanel.append(this.$profilePanel);

                } else {
                    this.$desktopContainerPanel.append(this.$profilePanel);
                }
            },
            update: function () {
                var _this = this;
                var resizeTimer = null;
                var resize = function () {
                    resizeTimer = null;

                    // Methods
                    _this.mixPanel();
                };

                $(window).on('resize', function () {
                    if (resizeTimer === null) {
                        resizeTimer = window.setTimeout(function () {
                            resize();
                        }, 300);
                    }
                }).resize();
            }
        };

        /* -----------------------------
         * On DOM ready functions
         * ---------------------------*/

        $(document).ready(function () {
            CRUMINA.preloader();

            CRUMINA.perfectScrollbarInit();

            // Row background animation
            if ($('.call-to-action-animation').length) {
                CRUMINA.CallToActionAnimation();
            }

            if ($('.img-scale-animation').length) {
                CRUMINA.ImgScaleAnimation()
            }

            if ($('.subscribe-animation').length) {
                CRUMINA.SubscribeAnimation()
            }

            if ($('.planer-animation').length) {
                CRUMINA.PlanerAnimation()
            }

            if ($('.contact-form-animation').length) {
                CRUMINA.ContactAnimationAnimation()
            }

            // Run scripts only if they included on page.

            if (typeof $.fn.gifplayer !== 'undefined') {
                $('.gif-play-image').gifplayer();
            }
            if (typeof $.fn.mediaelementplayer !== 'undefined') {
                $('#mediaplayer').mediaelementplayer({
                    "features": ['prevtrack', 'playpause', 'nexttrack', 'loop', 'shuffle', 'current', 'progress', 'duration', 'volume']
                });
            }

            CRUMINA.responsive.init();

        });

    })(jQuery);
});